﻿using System;
using Reactor.Customization;
using Reactor.Exceptions;
using Reactor.Messaging;

namespace Reactor.ServiceGrid.ServiceEntities
{
    public abstract class ManagedReactorService : ReactorServiceBase
    {
        #region Fields

        private PointToPointChannel _primaryInputChannel;

        #endregion

        protected ManagedReactorService()
        {
            if(InitializationCustomizationManager.ProposedServiceIdentifier == null)
                throw new FatalException("No ServiceIdentifier found to create service with.");

            Identifier = InitializationCustomizationManager.ProposedServiceIdentifier;
            InstanceIdentifier = InitializationCustomizationManager.ServiceInstanceIdentifier;
        }

        #region Overrides of ReactorServiceBase

        public override void Start()
        {
            base.Start();

            OnStarted();
        }

        /// <summary>
        /// Gets or sets the primary input queue.
        /// </summary>
        /// <value>The primary input queue.</value>
        public override PointToPointChannel PrimaryInputChannel
        {
            get { return _primaryInputChannel ?? (_primaryInputChannel = PointToPointChannel.CreateNameForManagedServiceInputChannel(Identifier)); }
            set { _primaryInputChannel = value; }
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the service instance identifier.
        /// </summary>
        /// <value>The service instance identifier.</value>
        public Guid InstanceIdentifier { get; set; }

        #endregion

        /// <summary>
        /// Called when the service is started. This signals concrete implementations to perform their 
        /// intended purpose.
        /// </summary>
        protected abstract void OnStarted();
    }
}
